package com.ruoyi.framework.config;



import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ruoyi.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * mybatis-plus 字段自动填充处理
 *
 * @author 轻描淡写 linkxs@qq.com
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            String userName = SecurityUtils.getUsername();
            if (StringUtils.isNotBlank(userName)) {
                this.strictInsertFill(metaObject, "createBy", String.class, userName);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        this.strictInsertFill(metaObject, "createTime", Date::new, Date.class);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            String userName = SecurityUtils.getUsername();
            if (StringUtils.isNotBlank(userName)) {
                this.strictUpdateFill(metaObject, "updateBy", String.class, userName);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        this.strictUpdateFill(metaObject, "updateTime", Date::new, Date.class);
    }
}